package laki.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class AddCustomerService {
	public static int CustomerId = 10;
	private int previousId;
	private int currentId;
	
	public String addCustomer(String customerName , Connection con){
		try{
			if(con == null){
				return "connection has to create";
			}
			else
			{
				Statement stmt = con.createStatement();
				String previousIdQ = "SELECT CustomerId FROM customer ORDER BY CustomerId DESC LIMIT 1";
				ResultSet rs = stmt.executeQuery(previousIdQ);
				System.out.println("entering point");
				System.out.println(rs.first());
				if(!rs.first()){
					System.out.println("entered");
					setpreviousId(CustomerId);
					System.out.println(" "+getpreviousId());
					String sql = "INSERT INTO customer (CustomerName ,CustomerId ) VALUES ('"+customerName+"', "+getpreviousId()+")";
					stmt.executeUpdate(sql);
				}
				else {
					System.out.println("entered to else");
						System.out.println("entered to while");
						setpreviousId(rs.getInt("CustomerId"));
						int i = getpreviousId();
						setCurrentId(++i);
						System.out.println(" "+getCurrentId());
						String sql = "INSERT INTO customer (CustomerName ,CustomerId ) VALUES ('"+customerName+"', "+getCurrentId()+")";
						stmt.executeUpdate(sql);
						
				}
				System.out.println("I am here now");
				return "customer name successfully added";
			}	
		}catch(SQLException se){
		      //Handle errors for JDBC
		      se.printStackTrace();
		      return "";
		   }
		
	}
	
	public int getpreviousId() {
		return previousId;
	}

	public void setpreviousId(int previousId) {
		this.previousId = previousId;
	}

	public int getCurrentId() {
		return currentId;
	}

	public void setCurrentId(int currentId) {
		this.currentId = currentId;
	}
}
